package com.chain.BrotherExchange.utils;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.support.annotation.DrawableRes;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.Target;
import com.chain.BrotherExchange.R;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class ImageViews {

    public static void load(String url, ImageView imageView) {
        load(url, imageView, true);
    }

    public static void load(String url, ImageView imageView, boolean skipMemoryCache) {
        Glide.with(imageView.getContext())
                .load(url)
                .crossFade()
                .skipMemoryCache(skipMemoryCache)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(imageView);
    }

    public static void load(String url, ImageView imageView, @DrawableRes int placeholder) {
        Glide.with(imageView.getContext()).load(url).dontAnimate()
                .skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.ALL)
                .placeholder(placeholder).into(imageView);
    }

    public static void load(Uri uri, ImageView imageView) {
        Glide.with(imageView.getContext()).load(uri).into(imageView);
    }

    // 加载图片并保存至本地
    public static void loadAndSaveLocal(String url, Activity context) {

        new Thread(() -> {
            try {
                Bitmap bitmap = Glide.with(context)
                        .load(url)
                        .asBitmap()
                        .into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                        .get();
                if (bitmap != null) {
                    saveImageToGallery(context, bitmap);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

    // 保存相册到相册
    public static void saveImageToGallery(Activity context, Bitmap bmp) {
        // 首先保存图片
        File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsoluteFile();
        String fileName = context.getResources().getString(R.string.app_name);
        File appDir = new File(file, fileName);
        if (!appDir.exists()) {
            appDir.mkdirs();
        }

        String imageName = System.currentTimeMillis() + ".jpg";
        File currentFile = new File(appDir, imageName);
        FileOutputStream fos = null;

        try {
            fos = new FileOutputStream(currentFile);
            bmp.compress(Bitmap.CompressFormat.JPEG, 90, fos);
            fos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                Uri.fromFile(new File(currentFile.getPath()))));
        context.runOnUiThread(() -> {
            Toast.makeText(context, "图片保存至" + currentFile.getPath(), Toast.LENGTH_SHORT).show();
        });
    }

    public void savePicture(Bitmap bm, String fileName) {

        File foder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/test");
        if (!foder.exists()) {
            foder.mkdirs();
        }
        File myCaptureFile = new File(foder, fileName);
        try {
            if (!myCaptureFile.exists()) {
                myCaptureFile.createNewFile();
            }
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
            bm.compress(Bitmap.CompressFormat.JPEG, 90, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

